<?php

@header('Content-Type: text/html; charset=UTF-8');
include("../includes/common.php");

// 若你的后台用的是 $islogin2 作为管理员登录标识（常见于该类项目），保留如下判断；否则按实际逻辑替换
if($islogin==1){}else loginmsg('请登录后再操作！');
$pluginsRoot = realpath(__DIR__ . '/../plugins'); // 绝对路径
if (!$pluginsRoot || !is_dir($pluginsRoot)) {
    $pluginsRoot = __DIR__ . '/../plugins';
}

// 安全工具函数
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision).' '.$units[$pow];
}
function dirSize($dir) {
    $size = 0;
    if (!is_dir($dir)) return 0;
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
    foreach ($it as $file) { $size += $file->getSize(); }
    return $size;
}
function sanitizePluginName($name) {
    // 仅允许字母数字、下划线、短横线
    if (!preg_match('/^[A-Za-z0-9_-]+$/', $name)) return false;
    return $name;
}
function addDirToZip($dir, ZipArchive $zip, $basePathLen) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
    foreach ($iterator as $file) {
        $filePath = $file->getPathname();
        $localName = substr($filePath, $basePathLen + 1); // 以插件目录为根
        if ($file->isDir()) {
            // ZipArchive 在添加文件时会自动创建目录，这里一般无需手动 addEmptyDir
            continue;
        } else {
            $zip->addFile($filePath, $localName);
        }
    }
}

// 2) 下载打包动作
if (isset($_GET['action']) && $_GET['action'] === 'download') {
    $rawName = isset($_GET['name']) ? $_GET['name'] : '';
    $safeName = sanitizePluginName($rawName);
    if (!$safeName) {
        http_response_code(400);
        exit('非法的插件名');
    }

    $pluginDir = realpath($pluginsRoot . '/' . $safeName);
    // 必须确保真实路径在 pluginsRoot 下
    if (!$pluginDir || strpos($pluginDir, realpath($pluginsRoot)) !== 0 || !is_dir($pluginDir)) {
        http_response_code(404);
        exit('插件不存在');
    }

    if (!class_exists('ZipArchive')) {
        http_response_code(500);
        exit('服务器未启用 ZipArchive 扩展，无法打包下载');
    }

    // 直接内存中创建 zip 并输出（先存到临时文件，再读出给浏览器）
    $tmpZip = tempnam(sys_get_temp_dir(), 'plg_');
    $zip = new ZipArchive();
    if ($zip->open($tmpZip, ZipArchive::OVERWRITE) !== true) {
        http_response_code(500);
        exit('打包失败：无法创建 ZIP');
    }
    // 将整个插件目录打到 zip，保留顶层目录名
    $basePathLen = strlen(dirname($pluginDir));
    // 先创建顶层目录（为了 zip 内有一个目录包裹）
    $zip->addEmptyDir($safeName);
    // 把内容按 safeName/xxx 放进去
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pluginDir, FilesystemIterator::SKIP_DOTS));
    foreach ($iterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();
        $relPath = substr($filePath, strlen($pluginDir) + 1);
        $zip->addFile($filePath, $safeName . '/' . $relPath);
    }
    $zip->close();

    // 输出下载
    $downloadName = $safeName . '.zip';
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="'.$downloadName.'"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($tmpZip));
    readfile($tmpZip);
    @unlink($tmpZip);
    exit;
}

// 3) 扫描插件目录
$plugins = [];
if (is_dir($pluginsRoot)) {
    $dh = opendir($pluginsRoot);
    if ($dh) {
        while (($entry = readdir($dh)) !== false) {
            if ($entry === '.' || $entry === '..') continue;
            $full = $pluginsRoot . '/' . $entry;
            if (is_dir($full)) {
                $meta = [
                    'dir' => $entry,
                    'name' => $entry,
                    'version' => '',
                    'author' => '',
                    'description' => '',
                    'size' => formatBytes(dirSize($full)),
                ];
                // 可选的 plugin.json
                $jsonFile = $full . '/plugin.json';
                if (is_file($jsonFile)) {
                    $j = @json_decode(@file_get_contents($jsonFile), true);
                    if (is_array($j)) {
                        $meta['name'] = $j['name'] ?? $meta['name'];
                        $meta['version'] = $j['version'] ?? '';
                        $meta['author'] = $j['author'] ?? '';
                        $meta['description'] = $j['description'] ?? '';
                    }
                }
                $plugins[] = $meta;
            }
        }
        closedir($dh);
    }
}

// 4) 页面展示（layui 风格）
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>插件管理</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui-src/dist/css/layui.css">
  <style>
    body { background:#f7f7f7; }
    .container { max-width: 1100px; margin: 20px auto; padding: 0 12px; }
    .plugin-card { margin-bottom:12px; }
    .plugin-meta { color:#666; font-size:12px; margin-top:6px; }
    .desc { color:#555; margin-top:6px; }
    .ellipsis { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  </style>
</head>
<body>
<div class="container">
  <div class="layui-card">
    <div class="layui-card-header">插件列表（共 <?php echo count($plugins); ?> 个）</div>
    <div class="layui-card-body">
      <?php if (empty($plugins)) { ?>
        <div class="layui-text" style="color:#888">plugins 目录下没有发现插件</div>
      <?php } else { ?>
        <div class="layui-row layui-col-space12">
          <?php foreach ($plugins as $plg) { ?>
            <div class="layui-col-xs12 plugin-card">
              <div class="layui-card">
                <div class="layui-card-body">
                  <div class="layui-row">
                    <div class="layui-col-xs9">
                      <div class="layui-text" style="font-size:16px;font-weight:700;"><?php echo htmlspecialchars($plg['name']); ?></div>
                      <div class="plugin-meta">
                        目录：<?php echo htmlspecialchars($plg['dir']); ?>
                        <?php if ($plg['version']) { ?> | 版本：<?php echo htmlspecialchars($plg['version']); } ?>
                        <?php if ($plg['author']) { ?> | 作者：<?php echo htmlspecialchars($plg['author']); } ?>
                        | 大小：<?php echo htmlspecialchars($plg['size']); ?>
                      </div>
                      <?php if ($plg['description']) { ?>
                        <div class="desc"><?php echo htmlspecialchars($plg['description']); ?></div>
                      <?php } ?>
                    </div>
                    <div class="layui-col-xs3" style="text-align:right;">
                      <a class="layui-btn layui-btn-normal" href="?action=download&name=<?php echo urlencode($plg['dir']); ?>">下载</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          <?php } ?>
        </div>
      <?php } ?>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/layui-src/dist/layui.js"></script>
</body>
</html>
